import { IPSDESearchForm, IPSSearchBar, IPSAppDEMultiDataView, IPSAppDEField } from '@ibiz/dynamic-model-api';
import { CodeListServiceBase, throttle, ModelTool, Util } from 'ibiz-core'
import { MDViewInterface } from 'ibiz-core/src/interface/view/md-view';
import { AppGlobalService } from '../app-service/logic-service/app-global-action-service';
import { MainViewBase } from "./mainview-base";

/**
 * 多数据视图基类
 *
 * @export
 * @class MDViewBase
 * @extends {MainViewBase}
 * @implements {MDViewInterface}
 */
export class MDViewBase extends MainViewBase implements MDViewInterface {

    /**
     * 多数据部件是否单选
     *
     * @type {boolean}
     * @memberof MDViewBase
     */
    public isSingleSelect!: boolean;

    /**
     * 代码表服务对象
     *
     * @type {CodeListService}
     * @memberof MDViewBase
     */
    public codeListService!: CodeListServiceBase;

    /**
     * 查询参数
     *
     * @type {*}
     * @memberof MDViewBase
     */
    public queryParams: any = {};

    /**
     * 快速搜索值（TODO 后续删除）
     *
     * @type {string}
     * @memberof MDViewBase
     */
    public query: string = '';

    /**
     * 实际是否展开搜索表单
     *
     * @type {boolean}
     * @memberof MDViewBase
     */
    public isExpandSearchForm: boolean = false;

    /**
     * 快速分组是否有抛值
     *
     * @description 第一次不抛值，否则会导致多数据部件多次加载
     * @memberof MDViewBase
     */
    public isEmitQuickGroupValue: boolean = false;

    /**
     * 搜索表单实例
     *
     * @type {IBizSearchFormModel}
     * @memberof MDViewBase
     */
    public searchFormInstance !: IPSDESearchForm;

    /**
     * 快速搜索表单实例
     *
     * @type {IBizSearchFormModel}
     * @memberof MDViewBase
     */
    public quickSearchFormInstance !: IPSDESearchForm;

    /**
     * 搜索栏实例
     *
     * @type {IBizSearchBarModel}
     * @memberof MDViewBase
     */
    public searchBarInstance!: IPSSearchBar;

    /**
     * 可搜索字段名称
     * 
     * @type {(string)}
     * @memberof MDViewBase
     */
    public placeholder: string = "";

    /**
     * 快速分组值变化
     * 
     * @param {*} $event 事件源
     * @memberof MDViewBase
     */
    public quickGroupValueChange($event: any) {
        if ($event) {
            this.queryParams.quickGroupData = $event.data;
            if (this.isEmitQuickGroupValue) {
                this.onSearch($event);
            }
        }
        this.isEmitQuickGroupValue = true;
    }

    /**
     * 快速搜索
     *
     * @param {*} $event
     * @memberof MDViewBase
     */
    public onSearch($event: any): void { }

    /**
     * 快速搜索栏数据对象
     *
     * @memberof MDViewBase
     */
    public quickFormData: any;

    /**
     * 初始化日历视图实例
     * 
     * @param opts 
     * @memberof MDViewBase
     */
    public async viewModelInit() {
        await super.viewModelInit();
        this.searchFormInstance = ModelTool.findPSControlByName('searchform', this.viewInstance.getPSControls() || []) as IPSDESearchForm;
        this.quickSearchFormInstance = ModelTool.findPSControlByName('quicksearchform', this.viewInstance.getPSControls() || []) as IPSDESearchForm;
        this.searchBarInstance = ModelTool.findPSControlByType('SEARCHBAR', this.viewInstance.getPSControls() || []) as IPSSearchBar;
        this.isExpandSearchForm = this.viewInstance?.expandSearchForm ? true : false;
    }

    /**
     *  多数据视图初始化
     *
     * @memberof MDViewBase
     */
    public viewInit() {
        super.viewInit();
        // 初始化属性值
        this.queryParams.quickSearchValue = '';
        this.initQuickSearchPlaceholder();
    }

    /**
     *  初始化快速搜索栏空白填充内容
     *
     * @memberof MDViewBase
     */
    public initQuickSearchPlaceholder() {
        const quickSearchFields: Array<IPSAppDEField> = (this.viewInstance as IPSAppDEMultiDataView).getPSAppDataEntity()?.getQuickSearchPSAppDEFields() || [];
        if (quickSearchFields.length > 0) {
            quickSearchFields.forEach((field: IPSAppDEField, index: number) => {
                const _field: IPSAppDEField | null | undefined = (this.viewInstance as IPSAppDEMultiDataView).getPSAppDataEntity()?.findPSAppDEField(field.codeName);
                if (_field) {
                    this.placeholder += (this.$tl(_field.getLNPSLanguageRes()?.lanResTag, _field.logicName) + (index === quickSearchFields.length - 1 ? '' : ', '));
                }
            })
        }
    }

    /**
     * 快速搜索栏值变化
     *
     * @memberof MDViewBase
     */
    public quickFormValueChange($event: any) {
        this.quickFormData = $event;
        this.onSearch($event);
    }

    /**
     * 渲染快速搜索
     * 
     * @memberof MDViewBase
     */
    public renderQuickSearch() {
        if (!this.viewInstance?.enableQuickSearch) {
            return;
        }
        if (this.viewInstance?.viewStyle == "DEFAULT") {
            return this.renderDefaultQuickSearch();
        } else {
            return this.renderStyle2QuickSearch();
        }
    }

    /**
     * 渲染快速搜索(DEFAULT)
     *
     * @return {*} 
     * @memberof MDViewBase
     */
    public renderDefaultQuickSearch() {
        return (
            <template slot="quickSearch">
                <i-input class='app-quick-search' style='max-width: 400px;margin-top:4px;padding-left: 24px' search on-on-search={($event: any) => this.onSearch($event)} v-model={this.queryParams.quickSearchValue} placeholder={this.placeholder} />
            </template>
        )
    }

    /**
     * 渲染快速搜索过滤（带搜索表单）
     *
     * @param {('searchform' | 'searchbar' | string)} type
     * @param {*} [content]
     * @return {*}  {*}
     * @memberof MDViewBase
     */
    public renderDefaultQuickSearchFilter(content?: any): any {
        const barFilters: Array<any> = this.searchBarInstance?.getPSSearchBarFilters() || [];
        const searchformItem: Array<any> = this.searchFormInstance?.getPSDEFormItems() || [];
        let enableFilter = this.viewInstance?.enableFilter === true && barFilters.length > 0 || searchformItem.length > 0;
        const popoverClass: string = this.searchFormInstance ? 'searchform-popover' : this.searchBarInstance ? 'searchbar-popover' : '';
        return [
            <i-input class={{ 'app-quick-search': true, 'width-filter': enableFilter }} style='max-width: 400px;margin-top:4px;padding-left: 24px' search on-on-search={($event: any) => this.onSearch($event)} v-model={this.queryParams.quickSearchValue} placeholder={this.placeholder} />,
            <el-popover placement="bottom" popper-class={popoverClass} trigger="click" visible-arrow={false} on-hide={() => this.isExpandSearchForm = !this.isExpandSearchForm}>
                <i-button slot="reference" class={{ 'filter': true, 'is-expand': this.isExpandSearchForm, 'hidden-searchbtn': !enableFilter }} icon="ios-funnel" on-click={(e: any) => {
                    if (!this.isExpandSearchForm) {
                        throttle(() => (AppGlobalService.getInstance() as any).executeGlobalAction('ToggleFilter', undefined, undefined, undefined, e, undefined, this, undefined), [], this);
                    }
                }} />
                <div>{content}</div>
            </el-popover>
        ]
    }

    /**
     * 渲染快速搜索(STYLE2)
     *
     * @return {*} 
     * @memberof MDViewBase
     */
    public renderStyle2QuickSearch() {
        return <i-input slot="quickSearch" className='app-quick-search' style='max-width: 400px;margin-top:6px;padding-left: 24px' search enter-button on-on-search={($event: any) => this.onSearch($event)} v-model={this.queryParams.quickSearchValuery} placeholder={this.placeholder} />
    }

    /**
     * 计算目标部件所需参数
     *
     * @param {string} [controlType]
     * @returns
     * @memberof MDViewBase
     */
    public computeTargetCtrlData(controlInstance: any) {
        const { targetCtrlName, targetCtrlParam, targetCtrlEvent } = super.computeTargetCtrlData(controlInstance);
        if (Object.is(controlInstance.controlType, 'SEARCHFORM') || Object.is(controlInstance.controlType, 'SEARCHBAR')) {
            Object.assign(targetCtrlParam.dynamicProps, {
                isExpandSearchForm: this.isExpandSearchForm
            });
        } else {
            Object.assign(targetCtrlParam.staticProps, {
                mDCtrlActiveMode: this.viewInstance.mDCtrlActiveMode,
            });
        }
        return { targetCtrlName: targetCtrlName, targetCtrlParam: targetCtrlParam, targetCtrlEvent: targetCtrlEvent };
    }

    /**
     * 渲染搜索表单
     * @memberof MDViewBase
     */
    public renderSearchForm() {
        if (!this.searchFormInstance) {
            return
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.searchFormInstance);
        return this.$createElement(targetCtrlName, { slot: 'searchForm', props: targetCtrlParam, ref: this.searchFormInstance?.name, on: targetCtrlEvent });
    }

    /**
     * 渲染快速搜索表单
     * 
     * @memberof MDViewBase
     */
    public renderQuickSearchForm() {
        if (!this.quickSearchFormInstance) {
            return
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.quickSearchFormInstance);
        return this.$createElement(targetCtrlName, { slot: 'quickSearchForm', props: targetCtrlParam, ref: this.quickSearchFormInstance?.name, on: targetCtrlEvent });
    }

    /**
     * 渲染搜索栏
     * 
     * @memberof MDViewBase
     */
    public renderSearchBar() {
        if (!this.searchBarInstance) {
            return
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.searchBarInstance);
        Object.assign(targetCtrlParam.dynamicProps, {
            isExpandSearchForm: this.isExpandSearchForm
        });
        if (this.viewInstance?.viewStyle == "DEFAULT" && this.viewInstance?.enableQuickSearch) {
            return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: this.searchBarInstance?.name, on: targetCtrlEvent });
        } else {
            return this.$createElement(targetCtrlName, { slot: 'searchBar', props: targetCtrlParam, ref: this.searchBarInstance?.name, on: targetCtrlEvent });
        }
    }

    /**
     * 渲染快速分组
     * 
     * @memberof MDViewBase
     */
    public renderQuickGroup() {
        if (!this.viewInstance?.enableQuickGroup) {
            return;
        }
        let counterService: any;
        if (this.viewInstance?.getPSAppCounterRef?.()?.id) {
            counterService = Util.findElementByField(this.counterServiceArray, 'id', this.viewInstance?.getPSAppCounterRef?.()?.id)?.service;
        }
        const codeList = (this.viewInstance as IPSAppDEMultiDataView).getQuickGroupPSCodeList?.();
        return <div class="quick-group-container" slot="quickGroupSearch">
            <app-quick-group context={this.context} viewparams={this.viewparams} codeList={codeList} on-valuechange={this.quickGroupValueChange.bind(this)} counterService={counterService}></app-quick-group>
        </div>;
    }

    /**
     * 部件事件
     * @param ctrl 部件 
     * @param action  行为
     * @param data 数据
     * 
     * @memberof MDViewBase
     */
    public onCtrlEvent(controlname: string, action: string, data: any) {
        super.onCtrlEvent(controlname, action, data);
        if (Object.is(controlname, 'quicksearchform') && Object.is(action, 'valuechange')) {
            this.quickFormValueChange(data);
        }
    }
}
